<template>
    <div class="common-tabs-wrap homeDetailVue">
        <div class="fastHandle">
            <Button type="info" class="header-btn" @click="handleCreateAppointment">新建工单</Button>
            <Button
                :class="{ active: isAddDeviceModalVisible }"
                type="info"
                class="header-btn"
                v-if="faceAccess && faceAccess.length && hasFaceAccessPermission"
                @click="operateVisitor(true)">
                添加访客
            </Button>
        </div>
        <Collapse v-model="collapseStatus" class="margin-bottom-20">
            <Panel name="1">
                <div v-if="homeInfo" class="Panel-header"><span>{{ homeInfo.city + homeInfo.district + homeInfo.address }}</span> <sub v-show="collapseStatus.length === 0" style="top:-2.5px">（点击可展开，进行更多管理）</sub></div>
                <p slot="content">
                    <Row style="padding:0 15px 20px 20px;margin-bottom:19px;">
                        <Col span="16">
                            <div v-if="homeInfo">
                                <div class="home-sub-title home-info-item">房源基础信息</div>
                                <div class="home-info-item">租赁类型：{{ homeInfo && homeInfo.lease_type === 1 ? '分租（公区不支持设置预付费，不支持办理租客入住）' : '整租（不支持公摊）' }}</div>
                                <div class="home-info-item">房源地址：{{ util.concatLocation(homeInfo) }}</div>
                                <div class="home-info-item">小区：{{ homeInfo.block || '-'}}</div>
                                <div class="home-info-item">房源编号：{{ homeInfo.home_name }}</div>
                                <div class="home-info-item">公寓类型：{{ HomeTypeEnum ? HomeTypeEnum.properties[homeInfo.home_type].text : '-' }}</div>
                                <div class="home-info-item">所属门店：{{ refreshStore || storeName }}</div>
                                <div class="home-info-item">
                                    管家：
                                    <span v-for="keeper in homeInfo.users" :key="keeper.id">
                                        {{keeper.name}}
                                    </span>
                                </div>
                            </div>
                            <span v-else>&nbsp;</span>
                        </Col>

                        <Col span="8">
                            <div style="float:right;margin-right:0px;min-width:230px">

                                <div class="home-sub-title">房源常用操作</div>


                                <Row class="op-item">
                                    <Col span="24" class="op-label">
                                        <Button
                                        :class="{ active:isEleCfgVisible && currentTab=='elemeter-cfg' && !appointment && !afterSevice && !isDecorateModalVisible && !isAddDeviceModalVisible }"
                                        class="operate-btn"
                                        type="ghost"
                                        @click="showEleCommonCfg"
                                        v-pmis="25">房源用电配置</Button>

                                      <Button
                                        class="operate-btn"
                                        type="ghost"
                                        @click="showLockCommonCfg">房源安全配置</Button>

                                        <Button
                                        :class="{ active: isDecorateModalVisible }"
                                        class="operate-btn"
                                        type="ghost"
                                        v-pmis="28"
                                        @click="setDecorateModalVisible(true)">装修密码管理</Button>
                                    </Col>
                                </Row>

                                <Row class="op-item">
                                    <Col span="24">
                                        <Button
                                        :class="{ active: isAddDeviceModalVisible }"
                                        class="operate-btn"
                                        type="ghost"
                                        @click="showAddDeviceModal"
                                        v-pmis="">
                                        添加设备</Button>

                                        <Button
                                        class="operate-btn"
                                        type="ghost"
                                        @click="showEditManager"
                                        v-if="!isKeeper">
                                        更改管理者</Button>
                                    </Col>
                                </Row>

                                <!-- <Row class="op-item" v-if="faceAccess && faceAccess.length && hasFaceAccessPermission">
                                    <i-col span="24">
                                        <Button
                                        :class="{ active: isAddDeviceModalVisible }"
                                        class="operate-btn"
                                        type="ghost"
                                        @click="operateVisitor(true)">
                                        添加访客</Button>
                                    </i-col>
                                </Row> -->
                            </div>
                        </Col>
                    </Row>
                </p>
            </Panel>
        </Collapse>


        <Tabs type="card" v-model="currentTab" closable :animated="false" @on-tab-remove="removeTab" @on-click="handleTabChange" class="room-tabs">
            <TabPane label="房间列表" style="padding:20px 0;" :closable="false" name="room-list">
               <RoomList :home="home" />
            </TabPane>

            <!-- 门禁相关tab -->
            <TabPane
                v-for="item in activefaceAccessTabs"
                style="padding:20px"
                :closable="false"
                :label="item.label"
                :name="item.tabName"
                :key="item.type">
                <NoNamespaceTabs
                    v-if="item.loaded"
                    :home-id="home.id"
                    :client-id="home.client_id"
                    :type="item.type"
                    :faceAccess="faceAccess"
                />
            </TabPane>

            <TabPane label="电表通用配置" name="elemeter-cfg" v-if="isEleCfgVisible">
                <elemeterCommonCfg :branchId="homeInfo.branch_id" :homeId="home.id" :leaseType="home.lease_type"/>
            </TabPane>
            <TabPane label="房源安全配置" name="lock-config" v-if="lockConfigVisible">
                <home-lock-setting :branchId="homeInfo.branch_id" :homeId="home.id"/>
            </TabPane>
            <TabPane v-for="item in openChargeTab" :label="'房间 '+item.roomName+' / 充值记录'" :name="item.id+'chargeCfg'" :key="item.id+'chargeCfg'">
                <!-- recordType: 0 电表记录;  1 水表记录;   2 充值记录 -->
                <roomRecords :recordType="2" :roomId="item.id"/>
            </TabPane>
            <TabPane v-for="item in openElemeterTab" :label="'房间 '+item.roomName+' / 用电记录'" :name="item.id+'elemeterCfg'" :key="item.id+'elemeterCfg'">
                <!-- recordType: 0 电表记录;  1 水表记录;   2 充值记录 -->
                <roomRecords :recordType="0" :roomId="item.id" :home-pool-setting="homePoolSetting"/>
            </TabPane>
            <TabPane v-for="item in openWatermeterTab" :label="'房间 '+item.roomName+' / 用水记录'" :name="item.id+'watermeterCfg'" :key="item.id+'watermeterCfg'">
                <!-- recordType: 0 电表记录;  1 水表记录;   2 充值记录 -->
                <roomRecords :recordType="1" :roomId="item.id"/>
            </TabPane>

            <!-- 设备详情 -->
            <TabPane
                style="padding-bottom:20px"
                v-for="device in deviceTabs"
                :label="device.label"
                :name="device.tabName"
                :key="device.id">
                <device-detail :home-id="home.id" :device="device" :client-id="home.client_id" :room-id="device.room_id" ></device-detail>
            </TabPane>

            <TabPane v-for="item in openGateTab" :label="'房间 '+item.roomName+' / '+item.description" :name="item.uuid+''" :key='item.uuid'>
                <gateway :room='item' :home-id="homeInfo.id"></gateway>
            </TabPane>
            <TabPane v-for="item in openCollectorTab" :label="'房间 '+item.roomName+' / '+item.description" :name="item.uuid+''" :key='item.uuid'>
                <elecollector :room='item' :home-id="homeInfo.id"></elecollector>
            </TabPane>
            <TabPane v-for="item in openColdTab" :label="'房间 '+item.roomName+' / '+item.description" :name="item.uuid+''" :key='item.uuid'>
                <waterMeter :waterMeters='item' :home-id="homeInfo.id"></waterMeter>
            </TabPane>
            <TabPane v-for="item in openLockTab" :label="'房间 '+item.roomName+' / '+item.description" :name="item.uuid+''" :key='item.uuid'>
                <Lock :deviceInfo='item' :home-id="homeInfo.id"></Lock>
            </TabPane>
            <TabPane v-for="item in openEleTab" :label="'房间 '+item.roomName+' / '+item.description" :name="item.uuid+''" :key='item.uuid'>
                <elemeter :room='item' :home-id="homeInfo.id"></elemeter>
            </TabPane>
            <TabPane v-for="item in openWaterGateWayTab" :label="'房间 '+item.roomName+' / '+item.description" :name="item.uuid+''" :key='item.uuid'>
                <waterGateway :room='item' :home-id="homeInfo.id"></waterGateway>
            </TabPane>
            <!-- <TabPane v-for="item in openRepeaterTab" :label="'房间 '+item.roomName+' / '+item.description" :name="item.uuid+''" :key='item.uuid'>
                <repeater :room='item'></repeater>
            </TabPane> -->
            <TabPane v-for="item in openRoomCfg" :label="'房间 '+item.roomName+' / '+'用电设置'" :name="item.roomId+'roomCfg'" :key="item.roomId+'roomCfg'">
                <roomConfig :room='item'></roomConfig>
            </TabPane>
            <TabPane v-for="item in lockSettings" :label="'房间 '+item.roomName+' / '+'安全配置'" :name="item.roomId+'lockSetting'" :key="item.roomId+'lockSetting'">
                <room-lock-setting :room='item'></room-lock-setting>
            </TabPane>


            <TabPane v-for="item in openedTab" :label="getRoomName(item)" :name="item.id + 'roomDetail'" :key="item.id">
                <roomDetail @on-load-device="onlyLoadDevices" :home="home" :room="item" @openType="openType"/>
            </TabPane>
        </Tabs>

        <!-- 装修密码管理 -->
        <decoratePwd :visible="isDecorateModalVisible" :home="home" @on-close="setDecorateModalVisible(false)"/>

        <!-- 添加租客 -->
        <addVisitor v-model="isOpenAddVistorModal" :homeId="home && home.id"></addVisitor>

        <!-- 添加设备 -->
        <addDevice
            :homeId="home.id"
            :visible="isAddDeviceModalVisible"
            :rooms="home.rooms"
            :homeInfo="home"
            :devices="devices"
            @on-close="closeAddDevice"
            @on-load-device="onlyLoadDevices"
            @on-reload-room="loadData"  />

        <Modal :width="700" v-model="modal.appointmentVisible" footer-hide :mask-closable="false">
            <ticketCreate
                @on-close="modal.appointmentVisible = false"
                v-if="modal.appointmentVisible"
                fixedHome
                :ticket.sync="modal.ticket"
                :home="{home_type: home && home.home_type}"
                ></ticketCreate>
        </Modal>

        <Modal v-model="isShowPermissionModal" :width="500">
            <p slot="header">
                <span>权限受限</span>
            </p>
            <div slot="close"></div>
            <div style="text-align:left;">
                <p style="padding:4px 15px">尊敬的客户，为确保交付质量，云丁提供更专业的安装绑定服务。</p>
                <p style="padding:4px 15px">请预约工单，专业人员将上门为您绑定设备。</p>
                <p style="padding:4px 15px">如有疑问，请联系对接商务或拨打客服热线。感谢您的支持</p>
            </div>
            <div slot="footer" style="padding:0">
                <Button type="default" @click="isShowPermissionModal = false">返回</Button>
            </div>
        </Modal>


        <!-- 更改管理者 -->
        <edit-manager
            :visible="isVisibleEditManager" @on-close="closeEditManager" :homeName="homeInfo && homeInfo.home_name" :branchId="homeInfo && homeInfo.branch_id" :id="homeInfo && homeInfo.id" @changeManagerSuc="setManagerInfo"></edit-manager>
    </div>
</template>

<script>
import bus from '@/libs/event-bus'
import { HomeTypeEnum, RoomTypeEnum, DeviceTypeEnum } from '@/libs/const'
import { mapState } from 'vuex'
import { http, api } from '@/libs/http'
import util from '@/libs/util'
import roomDetail from './roomDetail.vue'
import elemeterCommonCfg from './elemeterCommonCfg.vue'
import roomRecords from './roomRecords.vue'
import decoratePwd from './decoratePwd.vue'
import addDevice from './addDevice.vue'
import elemeter from './elemeter.vue'
import gateway from './gateWay.vue'
import Lock from './lock.vue'
import waterMeter from './waterMeter.vue'
import elecollector from './elecollector.vue'
import waterGateway from './waterGateWay.vue'
// import repeater from './repeater.vue';
import roomConfig from './roomConfig.vue'
import editManager from './editManager.vue'
import ticketCreate from '../ticket/create-components/ticket-create'
import homeLockSetting from './components/home-lock-setting'
import roomLockSetting from './components/room-lock-setting'
import RoomList from './room-list/room-list'
import deviceDetail from './device-detail/device-detail-container'
import addVisitor from './add-visitor'
import { noNamespaceTabsMap } from './tabs/type.d.js'
import NoNamespaceTabs from './tabs/tabs-wrap.vue'
import { fetchRoom } from './room-list/util'

export default {
  name: 'homeDetail',
  components: {
    NoNamespaceTabs,
    deviceDetail,
    RoomList,
    roomDetail,
    elemeter,
    gateway,
    Lock,
    waterMeter,
    elecollector,
    waterGateway,
    // repeater,
    elemeterCommonCfg,
    decoratePwd,
    addDevice,
    // addDeviceModal,
    roomRecords,
    roomConfig,
    ticketCreate,
    editManager,
    homeLockSetting,
    roomLockSetting,
    addVisitor
  },
  props: {
    home: Object,
    room: Object,
    stores: Object
  },
  data () {
    return {
      homePoolSetting: null, // 房间公摊设置
      util,
      faceAccess: [],
      collapseStatus: [],
      homeInfo: null,
      HomeTypeEnum: HomeTypeEnum,
      noNamespaceTabs: [],
      faceAccessTabs: [
        { loaded: false, label: '访客登记', tabName: 'visitorRegister', type: 'visitorRegister' },
        { loaded: false, label: '门禁开门记录', tabName: 'accessOpenHistory', type: 'accessOpenHistory' },
        { loaded: false, label: '人员出入异常', tabName: 'accessError', type: 'accessError' }
      ],
      isOpenAddVistorModal: false, // 是否打开访客弹窗
      deviceTabs: [],
      // clientInfo: null,
      isShowPermissionModal: false, // 是否打开权限弹窗
      currentTab: 0,
      openedTab: [],
      openEleTab: [],
      openGateTab: [],
      openLockTab: [],
      openColdTab: [],
      openHotTab: [],
      openCollectorTab: [],
      openWaterGateWayTab: [],
      openRepeaterTab: [],
      openRoomCfg: [],
      lockSettings: [],

      openChargeTab: [],
      openElemeterTab: [],
      openWatermeterTab: [],

      ticket: {
        type: 3,
        location: this.home.city + this.home.district + this.home.address,
        id: this.home.id,
        homeType: this.home.home_type
      },

      appointment: false,
      afterSevice: false,
      isDecorateModalVisible: false,
      isEleCfgVisible: false,
      isAddDeviceModalVisible: false,
      lockConfigVisible: false,

      rooms: [],
      devices: [],
      hasLoadedAllRoom: false,
      modal: {
        appointmentVisible: false,
        serviceVisible: false,
        ticket: null,
        data: null
      },
      isLoadingRoomInfo: false,
      isVisibleEditManager: false,
      refreshStore: '' // 更改管理者，子组件传过来的 “所属门店” 值
    }
  },
  created () {
    this.initHomeDetail()
    this.fetchFaceAccess()
    bus.$on('open-room' + this.home.id, this.openRoom)
    bus.$on('open-device' + this.home.id, this.openType)
    bus.$on('refresh-room' + this.home.id, this.onRoomDeviceRefresh)
  },
  mounted () {
    this.loadData()
    if (this.room) {
      this.openRoom(this.room)
    }
  },

  watch: {
    room () {
      if (this.room.home_id === this.home.id) {
        this.openRoom(this.room)
      }
    },
    $route (n) {
      if (n) {
        this.openDeviceFromQuery()
      }
    },
    currentTab (name) {
      if (this.hasFaceAccessPermission) {
        const tab = this.faceAccessTabs.find(tab => tab.tabName === name)
        if (tab && !tab.loaded) tab.loaded = true
      }
    }
  },
  computed: {
    ...mapState({
      devicePermission: state => state.user.devicePermission,
      hasFaceAccessPermission: state => state.user.hasFaceAccessPermission
    }),
    activefaceAccessTabs () {
      if (this.hasFaceAccessPermission) return this.faceAccessTabs
      return []
    },
    storeName () {
      // util.log('this.home:', this.home)
      if (this.stores && this.stores.name) {
        return this.stores.name
      }
      return '总部'
    },
    refreshRoom () {
      return this.$store.state.room.refresh_room
    },
    permissions () {
      if (localStorage.permission) {
        return JSON.parse(localStorage.permission)
      } else {
        return {}
      }
    },
    isKeeper () {
      const { roleId } = this.$store.state.user
      return roleId === 104 || roleId === 103
    },
    userHasBranchs () {
      const { branches } = this.$store.state.user
      return !!branches.length
    }
  },
  methods: {
    /** 房间设备更新监听 */
    async onRoomDeviceRefresh (roomId, deviceId, newDeviceName) {
      /** 更改设备名称处理 */
      if (deviceId && newDeviceName) {
        if (this.deviceTabs.length === 0) return
        const deviceIndex = this.deviceTabs.findIndex(device => device.id === deviceId)
        if (deviceIndex < 0) return
        this.$set(this.deviceTabs[deviceIndex], 'label', `${this.deviceTabs[deviceIndex].prefix}${newDeviceName}`)
      } else {
        try {
          const room = await fetchRoom(roomId)
          if (!room) return
          this.openedTab.forEach((item, index) => {
            if (item.id === roomId) {
              this.$set(this.openedTab[index], 'leases', room.leases)
            }
          })
        } catch (err) {
          console.log(err)
        }
      }
    },
    handleTabChange (tabName) {
      if (!this.hasFaceAccessPermission) return
      const faceAccessTabIndex = this.faceAccessTabs.findIndex(tab => tab.tabName === tabName)
      if (faceAccessTabIndex > -1 && !this.faceAccessTabs[faceAccessTabIndex].loaded) {
        this.$set(this.faceAccessTabs[faceAccessTabIndex], 'loaded', true)
      }
    },
    async fetchFaceAccess () {
      try {
        if (!this.$store.state.user.hasFaceAccessPermission) return
        this.faceAccess = await http.req(api.face_access_of_home, [ this.home.id ], null, true)
      } catch (err) {
        console.log(err)
      }
    },
    /**
         * 打开无前置命名空间的tab
         */
    openNoNamespaceTab (type) {
      const label = noNamespaceTabsMap[type].name
      if (!label) this.$Message.error('无此tab')
      const tabName = 'noNamespaceTabs-x-' + type
      const hadOpen = this.noNamespaceTabs.find(r => r.tabName === tabName)
      if (!hadOpen) {
        this.noNamespaceTabs.push({ label, tabName, type })
      }
      this.currentTab = tabName
    },
    /**
        * 操作租客
        */
    operateVisitor (isOpen = true) {
      this.isOpenAddVistorModal = isOpen
    },
    initHomeDetail () {
      http.request(this, api.home_info, [this.home.id], null, res => {
        this.homeInfo = res
        console.log('房源详情--详情页', this.homeInfo)
      })
    },
    handleCreateService () {
      this.modal.data = {
        home: this.home,
        room_id: ''
      }
      this.modal.serviceVisible = true
    },
    handleCreateAppointment () {
      const { id, address, block, city, district, home_name, province, number } = this.home
      // 使用工单返回数据结构
      this.modal.ticket = {
        home_id: id,
        ticket_devices: [],
        ticket_product_statistics: [],
        subscribe: {},
        home_info: {
          address,
          block,
          city,
          district,
          home_name,
          province,
          number
        }
      }
      this.modal.appointmentVisible = true
    },
    /**
         * 从url中传入query，跳转到具体设备
         */
    openDeviceFromQuery () {
      const { roomId, deviceType, deviceId, roomName } = this.$route.query
      if (roomId && deviceId) {
        http.request(this, api.home_devices_info, [this.home.id], null, res => {
          this.devices = res
          const device = res.find(d => d.id === Number(deviceId))
          const openDevice = [ 10, 11 ].includes(Number(deviceType)) ? 'device' : Number(deviceType)
          this.openType(roomId, openDevice, Number(deviceId), roomName, null, device)
        })
      } else if (roomId) {
        this.openRoom({ id: roomId })
      }
    },
    /**
         * 公区会显示楼栋门禁, roomId使用device.room_id
         */
    async openType (roomId, type, id, roomName, roomInfo, home, device) {
      const homeInfo = home || this.homeInfo
      switch (type) {
        case 1:
          http.request(this, api.gateway_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }
            let has = false
            this.currentTab = res.uuid + ''

            for (let i in this.openGateTab) {
              if (res.uuid === this.openGateTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              this.openGateTab.push(res)
            }
          })
          break
        case 2:
          http.request(this, api.lock_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }

            let has = false

            this.currentTab = res.uuid + ''

            for (let i in this.openLockTab) {
              if (res.uuid === this.openLockTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              res.roomInfo = roomInfo
              res.homeInfo = homeInfo
              this.openLockTab.push(res)
            }
          })
          break
        case 3:
          http.request(this, api.elemeter_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }

            let has = false

            this.currentTab = res.uuid + ''
            for (let i in this.openEleTab) {
              if (res.uuid === this.openEleTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              this.openEleTab.push(res)
            }
          })
          break
        case 4:
          http.request(this, api.elecollector_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }
            let has = false
            this.currentTab = res.uuid + ''

            for (let i in this.openCollectorTab) {
              if (res.uuid === this.openCollectorTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              this.openCollectorTab.push(res)
            }
          })
          break
        case 5:
          http.request(this, api.watergateway_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }
            let has = false
            this.currentTab = res.uuid + ''

            for (let i in this.openWaterGateWayTab) {
              if (res.uuid === this.openWaterGateWayTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              this.openWaterGateWayTab.push(res)
            }
          })
          break
        case 6:
          http.request(this, api.watermeter_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }
            let has = false
            this.currentTab = res.uuid + ''

            for (let i in this.openColdTab) {
              if (res.uuid === this.openColdTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              this.openColdTab.push(res)
            }
          })
          break
        case 7:
          http.request(this, api.watermeter_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }
            let has = false
            this.currentTab = res.uuid + ''

            for (let i in this.openColdTab) {
              if (res.uuid === this.openColdTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              this.openColdTab.push(res)
            }
          })
          break

        case 8: // 中继器
          http.request(this, api.repeater_info, [roomId, id], null, (res, err) => {
            if (!res || err) {
              return
            }
            let has = false
            this.currentTab = res.uuid + ''

            for (let i in this.openRepeaterTab) {
              if (res.uuid === this.openRepeaterTab[i].uuid) {
                has = true
                break
              }
            }

            if (!has) {
              res.roomId = roomId
              res.id = id
              res.roomName = roomName
              this.openRepeaterTab.push(res)
            }
          })
          break

        case 107:
          let has7 = false
          this.currentTab = roomId + 'lockSetting'

          for (let i in this.lockSettings) {
            if (roomId + 'lockSetting' === this.lockSettings[i].roomId + 'lockSetting') {
              has7 = true
              break
            }
          }

          if (!has7) {
            this.lockSettings.push({ roomId, homeId: id, roomName })
          }
          break

        case 108:
          let has = false
          this.currentTab = roomId + 'roomCfg'

          for (let i in this.openRoomCfg) {
            if (roomId + 'roomCfg' === this.openRoomCfg[i].roomId + 'roomCfg') {
              has = true
              break
            }
          }

          if (!has) {
            this.openRoomCfg.push({ roomId, homeId: id, roomName })
          }
          break

        case 109:
          let has9 = false
          this.currentTab = roomId + 'chargeCfg'

          for (let i in this.openChargeTab) {
            if (roomId + 'chargeCfg' === this.openChargeTab[i].id + 'chargeCfg') {
              has9 = true
              break
            }
          }

          if (!has9) {
            this.openChargeTab.push({
              id: roomId,
              type: id,
              roomName
            })
          }
          break

        case 110:
          let has10 = false
          this.currentTab = roomId + 'elemeterCfg'

          for (let i in this.openElemeterTab) {
            if (roomId + 'elemeterCfg' === this.openElemeterTab[i].id + 'elemeterCfg') {
              has10 = true
              break
            }
          }

          if (!has10) { // 如果已打开tab中没有这个
            if (this.homePoolSetting === null) { // 如果之前没有获取过房间公摊设置，获取一遍
              await this.getHomePoolSetting()
            }

            this.openElemeterTab.push({
              id: roomId,
              type: id,
              roomName
            })
          }
          break

        case 111:
          let has11 = false
          this.currentTab = roomId + 'watermeterCfg'

          for (let i in this.openWatermeterTab) {
            if (roomId + 'watermeterCfg' === this.openWatermeterTab[i].id + 'watermeterCfg') {
              has11 = true
              break
            }
          }

          if (!has11) {
            this.openWatermeterTab.push({
              id: roomId,
              type: id,
              roomName
            })
          }
          break

        case 'device':
          // 查询是否打开过该设备
          const hadOpenDevice = this.deviceTabs.find(d => d.id === device.id)
          let deviceName
          if (device.cName) {
            deviceName = device.cName
          } else {
            const deviceInfo = DeviceTypeEnum.properties[+device.device_type]
            deviceName = device.description || deviceInfo.name
          }
          const prefix = device.device_type === DeviceTypeEnum.FACE_ACCESS
            ? device.isBuildingDevice ? '楼栋 / ' : ''
            : `房间 ${roomName} / `
          if (!hadOpenDevice) {
            // const room = this.rooms.find(room => room.id === roomId)
            this.deviceTabs.push({
              roomId,
              ...device,
              // isPublicRoom: room.room_type === 2,
              prefix,
              tabName: 'deviceTabs-x-' + device.id,
              label: `${prefix}${deviceName}`
            })
          }
          this.currentTab = 'deviceTabs-x-' + device.id
          break
      }
    },

    async getHomePoolSetting () { // 获取房间公摊
      try {
        const setting = await http.fetch(this, api.home_pool_setting_info, [this.home.id], null)
        if (setting) this.homePoolSetting = setting.use_pool
      } catch (err) {
        console.log(err)
        return null
      }
    },

    onlyLoadDevices () {
      util.log('onlyLoadDevices=========')
      // 更新房间存在的设备
      http.request(this, api.home_devices_info, [this.home.id], null, res => {
        this.devices = res
      })
    },

    // 加载房间列表
    loadData () {
      util.log('loaddata=========')
      this.openDeviceFromQuery()
    },

    showEleCommonCfg () {
      this.isEleCfgVisible = true
      this.currentTab = 'elemeter-cfg'
      // this.$store.commit('HOMEDETAIL_CURRENT','elemeter-cfg')
    },
    showLockCommonCfg () {
      this.lockConfigVisible = true
      this.currentTab = 'lock-config'
    },

    openRoom (room) {
      let has = false
      for (let i in this.openedTab) {
        if (room.id === this.openedTab[i].id) {
          has = true
          this.currentTab = room.id + 'roomDetail'
          break
        }
      }
      if (!has) {
        const { leases } = room
        if (this.isLoadingRoomInfo) return
        this.isLoadingRoomInfo = true
        http.request(this, api.room_info, [room.id], null, (res, err) => {
          if (!res || err) {
            this.isLoadingRoomInfo = false
            return
          }
          // 兼容租约异常
          this.openedTab.push({ ...res, leases })
          this.currentTab = room.id + 'roomDetail'
          this.isLoadingRoomInfo = false
        })
      }
    },

    getRoomName (room) {
      if (room.room_type === RoomTypeEnum.PUBLIC) return '公区'
      return '房间 ' + room.room_name
    },

    removeTab (id) {
      if (/-x-/.test(String(id))) {
        const tabName = id
        const resources = tabName.split('-x-')
        const res = this[resources[0]].filter(tab => tab.tabName !== tabName)
        this[resources[0]] = res
      }

      if (id === 'elemeter-cfg') {
        this.isEleCfgVisible = false
      }

      if (id === 'lock-config') {
        this.lockConfigVisible = false
      }

      for (let i in this.openedTab) {
        if (this.openedTab[i].id + 'roomDetail' === id) {
          this.openedTab.splice(i, 1)
          return
        }
      }

      for (let i in this.openWaterGateWayTab) {
        if (this.openWaterGateWayTab[i].uuid === id) {
          this.openWaterGateWayTab.splice(i, 1)
          return
        }
      }

      for (let i in this.openEleTab) {
        if (this.openEleTab[i].uuid === id) {
          this.openEleTab.splice(i, 1)
          return
        }
      }
      for (let i in this.openGateTab) {
        if (this.openGateTab[i].uuid === id) {
          this.openGateTab.splice(i, 1)
          return
        }
      }
      for (let i in this.openColdTab) {
        if (this.openColdTab[i].uuid === id) {
          this.openColdTab.splice(i, 1)
          return
        }
      }
      for (let i in this.openCollectorTab) {
        if (this.openCollectorTab[i].uuid === id) {
          this.openCollectorTab.splice(i, 1)
          return
        }
      }

      for (let i in this.openLockTab) {
        if (this.openLockTab[i].uuid === id) {
          this.openLockTab.splice(i, 1)
          return
        }
      }
      for (let i in this.openRoomCfg) {
        if (this.openRoomCfg[i].roomId + 'roomCfg' === id) {
          this.openRoomCfg.splice(i, 1)
          return
        }
      }
      for (let i in this.lockSettings) {
        if (this.lockSettings[i].roomId + 'lockSetting' === id) {
          this.lockSettings.splice(i, 1)
          return
        }
      }
      for (let i in this.openChargeTab) {
        if (this.openChargeTab[i].id + 'chargeCfg' === id) {
          this.openChargeTab.splice(i, 1)
          return
        }
      }
      for (let i in this.openElemeterTab) {
        if (this.openElemeterTab[i].id + 'elemeterCfg' === id) {
          this.openElemeterTab.splice(i, 1)
          return
        }
      }
      for (let i in this.openWatermeterTab) {
        if (this.openWatermeterTab[i].id + 'watermeterCfg' === id) {
          this.openWatermeterTab.splice(i, 1)
          return
        }
      }
    },

    setDecorateModalVisible (v) {
      this.isDecorateModalVisible = v
    },

    showAddDeviceModal () {
      if (!this.devicePermission) {
        this.isShowPermissionModal = true
        return
      }
      this.isAddDeviceModalVisible = true
      this.onlyLoadDevices()
    },

    closeAddDevice () {
      this.isAddDeviceModalVisible = false
    },

    // reloadRoom(roomId) {
    //     http.request(this, api.room_info, [roomId], null, (res, err) => {
    //         if (res) {
    //             for (let i in this.rooms) {
    //                 if (this.rooms[i].id == roomId) {
    //                     this.rooms.splice(i, 1, res)
    //                     break
    //                 }
    //             }

    //             if (res.devices) {
    //                 for (let item of res.devices) {
    //                     if (!this.isInDevices(item.id)) {
    //                         this.devices.push(item)
    //                     }
    //                 }
    //             }
    //         }
    //     })

    //     this.$emit('on-update')
    // },

    isInDevices (id) {
      for (let item of this.devices) {
        if (item.id === id) {
          return true
        }
      }
      return false
    },

    showEditManager () {
      this.isVisibleEditManager = true
    },

    closeEditManager () {
      this.isVisibleEditManager = false
    },

    setManagerInfo (info) {
      this.refreshStore = info.shop
      this.homeInfo.users = info.manager
    }
  },
  beforeDestroy () {
    bus.$off('open-room' + this.home.id, this.openRoom)
    bus.$off('open-device' + this.home.id, this.openType)
    bus.$off('refresh-room' + this.homeId, this.onRoomDeviceRefresh)
  }
}
</script>

<style lang="less">
@baseGreen: #05bac5;
.home-wrap {
    margin: 0;
}
.op-wrap {
    height: 200px;
}
.op-item {
    padding: 0 0 5px;
}
.op-label {
    padding: 0 5px 0 0;
}

.item-right {
    text-align: left;
}

.room-tabs {
    margin:20px 0 0;
    // border-bottom:1px solid #e9eaec;
}

.Panel {
    &-header {
        position: relative;
        top: -50px;
        left: 25px;
        width: 80%;
        height: 50px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}

.ivu-tabs-tabpane > div {
    visibility: visible !important;
}
.home-sub-title {
    font-weight: bold;
    margin-bottom: 12px;
}
.home-info-item {
    margin-bottom: 12px;
}

.operate-btn {
    padding: 0;
    margin-bottom: 12px;
    width: 130px;
    height: 40px;
    margin-right: 10px;
}

.operate-btn:hover,
.operate-btn.active {
    color: #fff !important;
    background-color: @baseGreen!important;
}

.header-btn {
    float: right;
    margin: 9px 10px 0 0;
    &:nth-child(1) {
        margin-right: 30px;
    }
}

.fastHandle {
    position: absolute;
    right: 0;
    top: 46px;
    z-index: 2;
}
.homeDetailVue .ivu-collapse-header {
    border-left: 5px solid #05bac5;
    height: 50px !important;
    line-height: 50px !important;
    font-size: 18px !important;
    background-color: #efeff1 !important;
    font-weight: 700;
    padding-left:20px !important;
}

</style>
